<template>
    <div>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="id" label="ID" width="60" />
            <el-table-column prop="language_tag" label="语言标签" width="100" />
            <el-table-column prop="code" label="国际化标识" width="180" />
            <el-table-column prop="message" label="文本值" width="180" />
            <el-table-column prop="remarks" label="备注" width="180" />
            <el-table-column prop="created_at" label="创建时间" width="180" />
            <el-table-column fixed="right" label="Operations" min-width="120">
                <template #default="scope">
                    <el-button class="!ml-0" plain @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button link type="primary" size="small" @click="handleDelect(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination layout="prev, pager, next" :total="total" :page-size="10" @current-change="handlePageChange" />

        <el-dialog v-model="dialogFormVisible" title="新闻国际化管理" width="600" v-model:current-page="currentPage"
            :close-on-click-modal="false">
            <el-form :model="ruleForm" label-width="120px" label-position="right" ref="formRef">
                <!-- 国际化标识 -->
                <el-form-item label="国际化标识" prop="code" required>
                    <el-input v-model="ruleForm.code" placeholder="例如：HOME_TITLE" />
                </el-form-item>

                <!-- 语言文本（多语言数组） -->
                <el-form-item label="语言文本" prop="languageTexts" required>
                    <!-- 循环渲染多语言项 -->
                    <div v-for="(item, index) in ruleForm.languageTexts" :key="index" class="mb-3">
                        <el-row :gutter="20">
                            <el-col :span="5">
                                <el-input v-model="item.languageTag" placeholder="语言标签（如zh-CN）" />
                            </el-col>
                            <el-col :span="13">
                                <el-input v-model="item.message" placeholder="对应的文本值" />
                            </el-col>
                            <el-col :span="2">
                                <el-button type="danger" plain size="small" @click="removeLanguageItem(index)"
                                    :disabled="ruleForm.languageTexts.length <= 1">
                                    移除
                                </el-button>
                            </el-col>
                        </el-row>
                    </div>
                    <!-- 添加新语言项按钮 -->
                    <el-button type="primary" plain style="width: 500px; margin-top: 10px; border: 1px dashed #ccc"
                        @click="addLanguageItem">
                        + 添加语言
                    </el-button>
                </el-form-item>

                <!-- 备注 -->
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="ruleForm.remarks" style="width: 500px" :rows="2" type="textarea"
                        placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel" :disabled="loading">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="loading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { getI18nData, getI18nUpdata, getI18nDelete } from '@/api/i18n'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'


const formRef = ref<FormInstance | null>(null)
const loading = ref(false)
const tableData = ref<I18nItem[]>([])
const dialogFormVisible = ref(false)
const total = ref(0)
const currentPage = ref(1)


const handlePageChange = (value: number) => {
    fetchData(value)
}
//后端接口数据类型
interface LanguageText {
    languageTag: string
    message: string
}

interface RuleForm {
    code: string
    remarks: string
    languageTexts: LanguageText[]
}

const ruleForm = reactive<RuleForm>({
    code: '',
    remarks: '',
    languageTexts: [
        { languageTag: '', message: '' }
    ]
})

const addLanguageItem = () => {
    ruleForm.languageTexts.push({ languageTag: '', message: '' })
}

const removeLanguageItem = (index: number) => {
    if (ruleForm.languageTexts.length > 1) {
        ruleForm.languageTexts.splice(index, 1)
    }
}

// 编辑处理
const handleEdit = (row: I18nItem) => {

    ruleForm.code = row.code
    ruleForm.remarks = row.remarks || ''

    ruleForm.languageTexts = [
        {
            languageTag: row.language_tag,
            message: row.message
        }
    ]

    dialogFormVisible.value = true
}

// 取消
const handleCancel = () => {
    dialogFormVisible.value = false
    if (formRef.value) {
        formRef.value.resetFields()

        ruleForm.languageTexts = [{ languageTag: '', message: '' }]
    }
}

// 提交
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        loading.value = true

        // 后端要求的参数
        const requestData = {
            code: ruleForm.code,
            remarks: ruleForm.remarks,
            languageTexts: ruleForm.languageTexts
        }

        // 调用编辑接口传参
        const response = await getI18nUpdata(requestData)
        console.log('编辑接口返回数据', response)

        if (response.code === 200) {
            ElMessage.success('修改成功')
            dialogFormVisible.value = false
            fetchData(currentPage.value)
        } else {
            ElMessage.error(response.message || '修改失败，请重试')
        }

    } catch (error: any) {
        console.log('操作失败:', error)
        if (error.name !== 'ValidateError') {
            ElMessage.error('网络错误或接口异常，请稍后重试')
        }
    } finally {
        loading.value = false
    }
}

const handleDelect = async (row: I18nItem) => {
    try {
        const res = await getI18nDelete(row.code)
        console.log('删除接口返回数据', res)
        if (res.code === 200) {
            ElMessage.success('删除成功')
            fetchData(currentPage.value)
        } else {
            ElMessage.error(res.message || '删除失败，请重试')
        }
    } catch (error: any) {
        console.error('删除失败:', error)
        ElMessage.error(error.message || '删除失败，请重试')
    }
}

// 数据类型定义
interface I18nItem {
    code: string
    created_at: string
    id: string
    language_tag: string
    message: string
    remarks: string
}

interface I18nData {
    records: I18nItem[]
    total: number
}

const fetchData = async (current:number) => {
    try {
        const params = { current: current + '', currentSize: '10' }
        const res = await getI18nData<I18nData>(params)
        tableData.value = res.data.records
        total.value = res.data.total
    } catch (error) {
        console.error('获取数据失败:', error)
        ElMessage.error('获取数据失败，请刷新页面')
    }
}

onMounted(() => {
    fetchData(1)
})
</script>

<style scoped>
.mb-3 {
    margin-bottom: 12px;
}
</style>